package world.hezi.handlers;

import world.hezi.minecraft.MCPing;
import world.hezi.minecraft.MCPingOptions;
import world.hezi.minecraft.MCPingResponse;
import kotlin.coroutines.CoroutineContext;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.ListeningStatus;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.MessageEvent;
import org.jetbrains.annotations.NotNull;
import world.hezi.utils.CommonUtil;

import java.io.IOException;
import java.util.stream.Collectors;

/**
 * @author wangzijian
 * @since 2023/8/9 16:25
 */
public class MinecraftServerHandlers extends SimpleListenerHost {
    @Override
    public void handleException(@NotNull CoroutineContext context, @NotNull Throwable exception){
    }
    @NotNull
    @EventHandler
    public ListeningStatus onMessage(@NotNull MessageEvent event) throws Exception {
        String message = event.getMessage().contentToString();
        Contact contact = event.getSubject();
        message = message.toLowerCase();
        try {
            if (message.trim().indexOf("slp") == 0
                    ||message.trim().indexOf("服务器状态") == 0
                    ||message.trim().indexOf("在线人数") == 0){
                String[] strings = message.split(" ");
                if (strings.length <= 1){
                    MCPingOptions options = MCPingOptions.builder()
                            .hostname("192.144.157.195")
                            .port(25565)
                            .build();
                    sendSlp(contact,options);
                }else {
                    String[] split = strings[1].split(":");
                    if (split.length == 1){
                        split = new String[]{split[0],"25565"};
                    }
                    MCPingOptions options = MCPingOptions.builder()
                            .hostname(split[0])
                            .port(Integer.parseInt(split[1]))
                            .build();
                    sendSlp(contact,options);
                }
            }
        }catch (Exception e){
            contact.sendMessage("服务器连接失败！"+"\n"+ CommonUtil.getException(e));
        }
        return ListeningStatus.LISTENING;
    }

    private void sendSlp(Contact contact, MCPingOptions options){
        try {
            MCPingResponse mcPingResponse = MCPing.getPing(options);
            contact.sendMessage(mcPingResponse.getDescription().getStrippedText()
                    + "  --  "
                    + mcPingResponse.getPlayers().getOnline()
                    + "/" + mcPingResponse.getPlayers().getMax()
                    + "  " + mcPingResponse.getPing()+"ms"
                    +"\n"+
                    mcPingResponse.getPlayers().getSample().stream().map(MCPingResponse.Player::getName).collect(Collectors.toList()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
